<?php
namespace app\analysis\controller\ozon;

use app\common\model\shop\PlatformModel;
use app\common\model\shop\ShopsModel;
use app\common\service\shop\OzonReport;
use think\admin\Controller;
use think\App;


/**
 * 财务报表
 * @Description
 * @package app\analysis\controller
 * @author xuli
 * @date 2024-12-12 10:22
 */
class Finance extends Controller
{
    public $platform_info = null;
    public $platform_id = 0;
    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->platform_info = PlatformModel::mq()->where(['code' => PlatformModel::OZON_CODE])->find();
        $this->platform_id = $this->platform_info['id'] ?? 0;
    }

    /**
     * 财务报表
     * @auth true
     * @menu true
     */
    public function index()
    {
        // 获取店铺列表
        $this->check_account = true;
        $shop_list = ShopsModel::mq()->where(['platform_id' => $this->platform_id, ])->column('name', 'id');
        $this->assign("shop_list", $shop_list);
        $this->fetch();
    }

    /**
     * 获取财务报表数据
     */
    public function getFinanceList()
    {
        $shop_id = $this->request->param('shop_id', 0);
        //$report_time = $this->request->param('report_time', '2023-01-01 - 2024-12-31');
        $report_time = $this->request->param('report_time', '');
        $page = $this->request->param('page', 1);
        $page_size = $this->request->param('limit', 15);
        if(!$shop_id) {
            return json(['code' => 0, 'msg' => '', 'data' => [], 'count' => 0]);
        }
        if(empty($report_time)) {
            return json(['code' => 0, 'msg' => '', 'data' => [], 'count' => 0]);
        }

        $shop_info = ShopsModel::mq()->where(['id' => $shop_id])->find();

        // 获取平台配置参数
        if(empty($shop_info['client_id']) || empty($shop_info['api_key'])) {
            return json(['code' => 0, 'msg' => '', 'data' => [], 'count' => 0]);
        }

        $report_time = explode(' - ', $report_time);

        $form_time = date('c', strtotime($report_time[0] . ' 00:00:00'));
        $to_time = date('c', strtotime($report_time[1] . ' 23:59:59'));
        $form_time = substr($form_time, 0, -6) . '.000Z';
        $to_time = substr($to_time, 0, -6) . '.000Z';

        $where = [
            'from' => $form_time,
            'to' => $to_time,
        ];

        $report_model = new OzonReport(['client_id' => $shop_info['client_id'], 'api_key' => $shop_info['api_key']]);
//        $report_model = new OzonReport(['client_id' => '2297471', 'api_key' => '144127bb-109f-433e-b0ec-af858cb77eb7']);
        $data = $report_model->finance_cash_flow_statement($where, $page_size, $page);
        $data = $data['data'];

        foreach ($data['details'] as &$value) {
            $dateTime = new \DateTime($value['period']['begin']);
            $dateTime->setTimezone(new \DateTimeZone('UTC'));
            $value['period']['begin'] = $dateTime->format('Y-m-d H:i:s');

            $dateTime = new \DateTime($value['period']['end']);
            $dateTime->setTimezone(new \DateTimeZone('UTC'));
            $value['period']['end'] = $dateTime->format('Y-m-d H:i:s');

            if(!empty($value['services'])) {
                foreach ($value['services']['items'] as &$vv) {
                    $vv['service_name'] = self::servicesArr()[$vv['name']] ?? '';
                }
            }

            if(!empty($value['others'])) {
                foreach ($value['others']['items'] as &$vv) {
                    $vv['others_name'] = self::otherArr()[$vv['name']] ?? '';
                }
            }
        }

        return json(['code' => 0, 'msg' => '', 'data' => $data['details'], 'count' => $data['page_count']]);
    }

    private static function servicesArr()
    {
        return [
            'MarketplaceServiceItemElectronicServiceStencil' => lang('模板'),
            'MarketplaceServiceItemElectronicServicesPromotionInSearch' => lang('搜索结果推广'),
            'MarketplaceServiceItemElectronicServicesBrandShelf' => lang('品牌货架'),
            'MarketplaceServiceBrandPromotion' => lang('品牌推广'),
            'MarketplaceServiceBrandCommission' => lang('品牌推广'),
            'MarketplaceServiceItemMarketingServices' => lang('营销服务'),
            'MarketplaceServiceItemOtherMarketAndTechService' => lang('其他销售和技术服务'),
            'MarketplaceReturnStorageServiceAtThePickupPointFbsItem' => lang('短期FBS退货安置'),
            'MarketplaceSaleReviewsItem' => lang('在平台上获得评论'),
            'MarketplaceServicePremiumCashbackIndividualPoints' => lang('卖家奖励'),
            'OperationMarketplaceServiceStorage' => lang('商品放置服务'),
            'MarketplaceServiceStockDisposal' => lang('从库存中处置'),
            'MarketplaceReturnDisposalServiceFbsItem' => lang('FBS处置'),
            'MarketplaceServiceItemFlexiblePaymentSchedule' => lang('灵活付款计划'),
            'MarketplaceServiceProcessingSpoilage' => lang('残次品处理'),
            'MarketplaceServiceProcessingIdentifiedSurplus' => lang('处理确定的盈余'),
            'MarketplaceServiceProcessingIdentifiedDiscrepancies' => lang('预定放置在仓库中的位置'),
            'MarketplaceServiceItemInternetSiteAdvertising' => 'Ozon'.lang('网站上的广告'),
            'MarketplaceServiceItemSubscribtionPremium' => lang('高级订阅'),
            'MarketplaceAgencyFeeAggregator3PLGlobalItem' => 'Ozon'.lang('代理费用'),
            'MarketplaceAgencyFeeAggregator3PLGlobal' => 'Ozon'.lang('代理费用'),
        ];
    }

    private static function otherArr()
    {
        return [
            'MarketplaceRedistributionOfAcquiringOperation' => lang('收单业务支付'),
            'MarketplaceSellerCompensationLossOfGoodsOperation' => lang('赔偿损失商品'),
            'MarketplaceSellerCorrectionOperation' => lang('调整服务成本'),
            'OperationCorrectionSeller' => lang('相互结算清点'),
            'OperationMarketplaceWithHoldingForUndeliverableGoods' => lang('商品不足的赔偿'),
            'OperationClaim' => lang('索赔费用'),
        ];
    }
}